package com.export.thread;

import com.aliyun.oss.OSSClient;
import com.export.bean.model.StateModel;
import com.export.config.ExportContansts;
import com.export.config.FileHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * Created by Studio on 2017/5/10.
 * 将压缩文件上传到OSS
 * 并删除原压缩文件
 */
@Component("UploadThread")
@Scope("prototype")
public class UploadThread extends Thread{

    private static final Logger logger = LoggerFactory.getLogger(UploadThread.class);
    private String fileName;
    private String filePath;
    private StateModel stateModel;

    public UploadThread(String fileName,String filePath,StateModel stateModel) {

        this.fileName = fileName;
        this.filePath = filePath;
        this.stateModel = stateModel;

    }

    @Override
    public void run() {

        logger.info(fileName);
        //上传到oss
        uploadFileToOSS(fileName,filePath);

        logger.info("Uploaded to the OSS successfully!/上传成功");
        String address = getAddress(ExportContansts.bucketName,ExportContansts.bucketNameFileName+fileName);
        logger.info(address);
        stateModel.setAddress(address);
        stateModel.setUploadstate();
        FileHandle.deleteFile(filePath);
    }

    private static void uploadFileToOSS(String fileName, String filePath){
        // endpoint以杭州为例，其它region请按实际情况填写
//        String endpoint = "http://"+ExportContansts.outerNetEndPointHANGZHOU;//外网地址
        String endpoint = "http://"+ExportContansts.innerNetEndPointHANGZHOU;//内网地址
        // accessKey请登录https://ak-console.aliyun.com/#/查看
        String accessKeyId = ExportContansts.accessKeyID;
        String accessKeySecret = ExportContansts.accessKeySecret;
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId ,accessKeySecret );
        // 上传文件
        ossClient.putObject(ExportContansts.bucketName,
                       ExportContansts.bucketNameFileName+fileName,
                            new File(filePath));
        // 关闭client
        ossClient.shutdown();
    }

    private static String getAddress(String bucketName, String fileName){
        return bucketName+'.'+ExportContansts.outerNetEndPointHANGZHOU+"/"+fileName;
//        return bucketName+'.'+ExportContansts.outerNetEndPointHANGZHOU+"/"+fileName;//内网地址
    }

}
